﻿using System.Activities;
using WFBot.Framework.Services;
using WFBot.Framework.Domain;
using System;
using Microsoft.Practices.Unity;

namespace WFBot.Workflow.Activities
{
    public class PushQuestion : NativeActivity
    {
        public InArgument<string> Channel { get; set; }
        public InArgument<string> Question { get; set; }
        public InArgument<string> Type { get; set; }
        public InArgument<string> Options { get; set; }
        public InArgument<bool> IsIdentifier { get; set; }
        public OutArgument<string> Response { get; set; }

        protected override void Execute(NativeActivityContext context)
        {
            var wfService = context.GetExtension<IWorkflowService>();
            wfService.Push(new Message { 
                Channel = Channel.Get(context), 
                Sender = "WFBot",
                Type = MessageType.Question,
                QuestionType = Type.Get(context),
                Origin = MessageOrigin.Server,
                Body = Question.Get(context),
                Options = Options.Get(context)
            });
            wfService.Bookmark(Channel.Get(context));
            context.CreateBookmark(Channel.Get(context), Answered);
        }

        void Answered(NativeActivityContext context, Bookmark bookmark, object obj)
        {
            var message = (Message)obj;
            if (!string.IsNullOrWhiteSpace(message.Body))
            {
                var container = context.GetExtension<IUnityContainer>();
                var botService = container.Resolve<IBotService>();
                var question = new Question
                {
                    IsActive = true,
                    IsIdentifier = IsIdentifier.Get(context),
                    Text = Question.Get(context),
                    Options = Options.Get(context),
                    Type = (WFBot.Framework.Domain.QuestionType)Enum.Parse(typeof(WFBot.Framework.Domain.QuestionType), Type.Get(context), true)
                };
                botService.SaveVisitorResponse(Channel.Get(context), question, message.Body);
                Response.Set(context, message.Body);
            }
        }

        protected override bool CanInduceIdle { get { return true; } }

    }

    public class QuestionType
    {
        public const string FreeText = "freetext";
        public const string SingleSelection = "singleselection";
        public const string MultiSelection = "multiselection";
    }
}